<?php
namespace app\admin\controller;

use app\admin\model\Article as articleModel;
use app\admin\model\Category as cateModel;
use app\admin\model\Tag as tagModel;
use app\admin\validate\ArticleValidate;
use tool\Log;
use think\Db;

class Article extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $keywords = input('param.keywords');
            $where = [];
            if (!empty($keywords)) {
                $where[] = ['title', 'like', '%' . $keywords . '%'];
            }

            $article = new articleModel();
            $list = $article->getArticle($limit, $where);
            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }
            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }
    // 添加文章
    public function add()
    {
        if (request()->isPost()) {
            $param = input('post.');

            $validate = new articleValidate();
            if (!$validate->check($param)) {
                return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
            }
            $param['keyword'] = str_replace("，",",", strtolower($param['keyword']));


            // 把关键词分解
            $keyword = $param['keyword'];
            if(!empty($keyword)) {
                if(strpos($keyword,",")) {
                    $tags = explode(",", $keyword);  //判断是否存在逗号，如果存在就拆分成数组，否则就表示只一个关键词
                } else {
                    $tags = array($keyword);
                }
            }

            //$tagModel = new tagModel();
            // 把关键词$tags传到tag表中

                for ($i=0; $i<count($tags); $i++) {
                    $flag = Db::name('tag')->where('tagname', $tags[$i])->find();
                    if(!$flag) { //如果tag存在就不插入
                        Db::name('tag')->insert([
                            'tagname'  =>  $tags[$i],
                            'add_time' =>  date('Y-m-d H:i:s'),
                            'update_time' =>  date('Y-m-d H:i:s'),
                            'status' => 1
                        ]);
                        continue;
                    }
                }

            $article = new articleModel();
            $res = $article->addArticle($param);

            Log::write("添加文章：" . $param['title']);

            return json($res);
        }
        $cate = new cateModel();
        $cateList = $cate->order('id asc')->select();
        $this->assign('cateList', $cateList);
        return $this->fetch();
    }
    // 编辑文章
    public function edit()
    {
        if (request()->isPost()) {

            $param = input('post.');

            $validate = new articleValidate();
            if (!$validate->scene('edit')->check($param)) {
                return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
            }

            $article = new articleModel();
            $res = $article->editArticle($param);

            Log::write("编辑文章：" . $param['catname']);

            return json($res);
        }

        $id = input('param.id');
        $article = new articleModel();
        $cate = new cateModel();
        $cateList = $cate->order('id asc')->select();

        $this->assign([
            'item' => $article->getArticleById($id)['data'],
            'cateList'=> $cateList
        ]);

        return $this->fetch('edit');
    }

    /**
     * 删除文章
     * @return \think\response\Json
     */
    public function del()
    {
        if (request()->isAjax()) {
            $id = input('param.id');

            $article = new articleModel();
            $res = $article->delArticle($id);

            Log::write("删除文章：" . $id);
            return json($res);
        }
    }
    // 批量删除文章
    public function isDelAll() {
        if (request()->isAjax()) {
            $id = input('param.id');

            $article = new articleModel();
            if($article->where('id', 'in', $id)->delete()) {
                return reMsg('0','','删除成功');
            } else {
                return reMsg('-1','','删除失败');
            }
        }
    }
    /**
     * 上传图片
     */
    public function uploadPic() {
        // 获取表单上传文件
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move('./uploads/pic/');
        if($info){
            // $path1 =  $info->getExtension(); // 输出 jpg
            $path =  $info->getSavename();  // 输出 20160820\42a79759f284b767dfcb2a0197904287.jpg

            $realPath = '/uploads/pic/'.$path;
            $realPath = str_replace('\\','/',$realPath);
            // 成功上传后 返回上传信息
            return reMsg('0',$realPath,'图片上传成功');
        }else{
            // 上传失败返回错误信息
            return reMsg('-1','','图片上传失败');
        }
    }

}